<?php
/**
 *  💡 免责声明：本软件不得用于商业用途，仅做学习交流
 *  ⚠️ 权利声明：本软件由版权人提供产品技术支持
 *  📅 项目编号：NX2025-0135
 */
namespace App\Service\Notifications;

use App\Events\Notify;
use App\Models\User;
use App\Notifications\ActiveNotificationTemp;
use App\Notifications\OrderNotificationTemp;
use App\Notifications\SystemNotificationTemp;
use App\Service\BaseService;

class NotificationService extends BaseService
{
    public const SYSTEM = SystemNotificationTemp::class;

    public const ORDER = OrderNotificationTemp::class;

    public const ACTIVE = ActiveNotificationTemp::class;

    public function SystemNotify(User $user, $msg)
    {
        event(new Notify($user, Notify::SYSTEM, $msg));
    }

    public function SystemAllNotify($msg)
    {
        User::query()->where('status', 1)
            ->chunkById(200, function ($users) use ($msg) {
                foreach ($users as $user) {
                    event(new Notify($user, Notify::SYSTEM, $msg));
                }
            });
    }

    public function ActiveNotify($msg)
    {
        User::query()->where('status', 1)
            ->chunkById(200, function ($users) use ($msg) {
                foreach ($users as $user) {
                    event(new Notify($user, Notify::ACTIVE, $msg));
                }
            });
    }

    public function OrderNotify(User $user, $order, $msg, $type = 1)
    {
        $data = [
            'type' => $type,
            'msg' => $msg,
            'order' => $order->toArray(),
        ];
        event(new Notify($user, Notify::ORDER, $data));
    }

    public function getNotifyCount(User $user)
    {
        $notify = $user->unreadNotifications()->select('id');

        return [
            'system' => $notify->where('type', self::SYSTEM)->count(),
            'order' => $notify->where('type', self::ORDER)->count(),
            'active' => $notify->where('type', self::ACTIVE)->count(),
        ];
    }

    public function getNotify(User $user, $type = self::SYSTEM)
    {
        return $user->notifications()
            ->where('type', $this->notifyType($type))
            ->simplePaginate(request('perPage', 20));
    }

    public function readNotify(User $user, $ids)
    {
        $user->notifications()
            ->whereIn('id', $ids)
            ->first()->markAsRead();
    }

    public function allRead(User $user, $type)
    {
        $user->unreadNotifications()
            ->where('type', $this->notifyType($type))
            ->update(['read_at' => now()]);
    }

    private function notifyType($type)
    {
        switch ($type) {
            case 1:
                return self::SYSTEM;
                break;
            case 2:
                return self::ORDER;
                break;
            case 3:
                return self::ACTIVE;
                break;
        }
    }
}
